package com.mycompany.jsf100;

import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

@SessionScoped
@javax.inject.Named("myLogin") // default bean name would be 'login'
public class Login implements Serializable {

    @Inject
    Credentials credentials;

    private User user;

    public String login() {

        String nextPage = "loginErrorPage";

//        List<User> results = userDatabase.createQuery(
//                "select u from User u where u.username=:username and u.password=:password")
//                .setParameter("username", credentials.getUsername())
//                .setParameter("password", credentials.getPassword())
//                .getResultList();
//
//        if (!results.isEmpty()) {
//            user = results.get(0);
//        }
        // user with credetials test, test will be logged in
        if (credentials != null) {
            if ("test".equals(credentials.getUsername()) && "test".equals(credentials.getPassword())) {
                user = new User();
                user.setName(credentials.getUsername());
                user.setPassword(credentials.getPassword());
                System.out.println("user test, test is logged in :-)");

                String message = user.getName() + "! - you're logged in";
                FacesMessage facesMessage = new FacesMessage(message);
                FacesContext.getCurrentInstance().addMessage(null, facesMessage);

                nextPage = "page1";
            } else {
                String message = credentials.getUsername() + "  - no way";
                FacesMessage facesMessage = new FacesMessage(message);
                FacesContext.getCurrentInstance().addMessage(null, facesMessage);
            }
                
        }
        return nextPage;
    }

    public String logout() {
        user = null;
        System.out.println("user logged out");
        return "loginPage";
    }

    public boolean isLoggedIn() {
        return user != null;
    }

//    @Produces
//    @LoggedIn
//    User getCurrentUser() {
//        return user;
//    }
}
